<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>首页</title>
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css"
      crossorigin="anonymous"
    />
  </head>
  <body>
    <!-- 最外面要有container，才能使页面有响应式 -->
    <div class="container">
      <!-- 用于搜索的表单 -->
      <div
        style="
          display: flex;
          justify-content: space-between;
          align-items: flex-end;
        "
      >
        <form class="form-inline" style="margin-top: 40px">
          <div class="form-group mx-sm-3 mb-2">
            <input type="text" class="form-control name" placeholder="姓名" />
          </div>
          <button type="submit" class="btn btn-primary mb-2 search">
            搜索
          </button>
          <button type="submit" class="btn btn-primary mb-2 reset">重置</button>
        </form>

        <button
          type="button"
          class="btn btn-primary"
          data-toggle="modal"
          data-target="#exampleModal"
        >
          新增
        </button>
      </div>

      <table class="table table-bordered">
        <thead>
          <tr>
            <th scope="col">_id</th>
            <th scope="col">姓名</th>
            <th scope="col">年龄</th>
            <th scope="col">学号</th>
            <th scope="col">性别</th>
            <th scope="col">地址</th>
            <th scope="col">操作</th>
          </tr>
        </thead>
        <tbody></tbody>
      </table>

      <nav aria-label="Page navigation example">
        <ul class="pagination" style="justify-content: flex-end"></ul>
      </nav>

      <div
        class="modal fade"
        id="exampleModal"
        tabindex="-1"
        aria-labelledby="exampleModalLabel"
        aria-hidden="true"
      >
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title" id="exampleModalLabel">新增学员</h5>
              <button
                type="button"
                class="close"
                data-dismiss="modal"
                aria-label="Close"
              >
                <span aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">
              <form>
                <div class="form-group row">
                  <label for="addname" class="col-sm-2 col-form-label"
                    >姓名</label
                  >
                  <div class="col-sm-10">
                    <input type="text" class="form-control" id="addname" />
                  </div>
                </div>
                <div class="form-group row">
                  <label for="age" class="col-sm-2 col-form-label">年龄</label>
                  <div class="col-sm-10">
                    <input type="number" class="form-control" id="age" />
                  </div>
                </div>
                <div class="form-group row">
                  <label for="num" class="col-sm-2 col-form-label">学号</label>
                  <div class="col-sm-10">
                    <input type="number" class="form-control" id="num" />
                  </div>
                </div>
                <div class="form-group row">
                  <label for="sex" class="col-sm-2 col-form-label">性别</label>
                  <div class="col-sm-10">
                    <select class="custom-select mr-sm-2" id="sex">
                      <option selected disabled>请选择</option>
                      <option value="1">男</option>
                      <option value="2">女</option>
                    </select>
                  </div>
                </div>
                <div class="form-group row">
                  <label for="address" class="col-sm-2 col-form-label"
                    >地址</label
                  >
                  <div class="col-sm-10">
                    <input type="text" class="form-control" id="address" />
                  </div>
                </div>
              </form>
            </div>
            <div class="modal-footer">
              <button
                type="button"
                class="btn btn-secondary"
                data-dismiss="modal"
              >
                取消
              </button>
              <button
                type="button"
                class="btn btn-primary add"
                data-dismiss="modal"
              >
                确定
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script
      src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js"
      crossorigin="anonymous"
    ></script>
    <script>
      // 当前是第几页
      let current_page = 1;
      // 每页请求几条数据
      let page_size = 3;
      // 搜索的名字
      let name = "";

      // 封装成promise的请求
      const ajax = (url, data = {}, method = "GET") => {
        return new Promise((resolve, reject) => {
          $.ajax({
            url: "http://localhost:3000/api" + url,
            method,
            data,
            success(res) {
              resolve(res);
            },
          });
        });
      };

      const getTableData = async () => {
        const res = await ajax("/students/list", {
          current_page,
          page_size,
          name,
        });
        if (res.status === 0) {
          // 拼接表格数据
          let str = "";
          res.result.forEach((item) => {
            str += `
              <tr>
                <th>${item._id}</th>
                <th>${item.name}</th>
                <th>${item.age}</th>
                <th>${item.num ? item.num : "未知"}</th>
                <th>${item.sex === 1 ? "男" : "女"}</th>
                <th>${item.address}</th>
                <th>
                  <button type="button" class="btn btn-warning">编辑</button>
                  <button type="button" class="btn btn-danger" onclick="del('${
                    item._id
                  }')">删除</button>
                </th>
              </tr>
            `;
          });
          document.querySelector("tbody").innerHTML = str;

          // 拼接分页数据
          let str2 =
            '<li class="page-item"><a class="page-link" href="#">Previous</a></li>';
          // 计算得到总条数
          const total_page = Math.ceil(res.count / page_size);
          for (let i = 1; i <= total_page; i++) {
            str2 += `<li class="page-item"><a class="page-link" href="#" onclick="liclick(${i})">${i}</a></li>`;
          }
          str2 +=
            '<li class="page-item"><a class="page-link" href="#">Next</a></li>';
          $(".pagination").html(str2);
        }
      };

      window.onload = () => {
        getTableData();
      };

      // 点击页码的事件
      const liclick = (i) => {
        // console.log(i);
        // 改变当前第几页
        current_page = i;
        getTableData();
      };

      // 搜索事件
      $(".search").on("click", () => {
        // console.log($(".name").val());
        // 只要所搜索，需要将页码变成第一页
        current_page = 1;
        name = $(".name").val();
        getTableData();
      });

      // 重置
      $(".reset").on("click", () => {
        name = "";
        $(".name").val("");
        getTableData();
      });

      // 删除事件
      // 删除事件必须要加二次确认
      const del = async (id) => {
        const res = await ajax("/students/del", { id }, "POST");
        if (res.status === 0) {
          // 如果成功了不要刷新页面，应该是重新请求数据
          getTableData();
        } else {
          alert(res.msg);
        }
      };

      // 添加事件
      $(".add").on("click", async () => {
        // console.log({
        //   name: $("#addname").val(),
        //   age: $("#age").val(),
        //   num: $("#num").val(),
        //   sex: $("#sex").val(),
        //   address: $("#address").val(),
        // });
        const res = await ajax(
          "/students/add",
          {
            name: $("#addname").val(),
            age: $("#age").val(),
            num: $("#num").val(),
            sex: $("#sex").val(),
            address: $("#address").val(),
          },
          "POST"
        );
        if (res.status === 0) {
          getTableData();
        }
      });
    </script>
  </body>
</html>
